<script setup lang="ts">
// 引入必要的模块和组件
import { ExamService } from "@/service/ExamService";
import { apiClient } from "@/utils/apiClient";
import Button from 'primevue/button';
import Textarea from 'primevue/textarea';
import { onMounted, onUnmounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import AppFooter from "../../layout/AppFooter.vue";
import { CommonService } from "../common";
import ConfirmDialog from "../ConfirmDialog.vue";

// 定义引用变量
const confirmDialog = ref<InstanceType<typeof ConfirmDialog>>();
const dialogMessage = ref("正在提交考试");

const route = useRoute();
const router = useRouter();
const params = ref({
    sn: "",
    isMe: false,
});

// 定义用户和学生信息
const currentUser = ref({
    name: "",
    sn: "",
    r: 0,
});
const exam = ref({
    Id: 0,
    Title: "",
    Desc: "",
    Createtime: "",
    Enable: 1,
    Questions: "",
    StartAt: "", // 添加开始时间字段
    EndAt: "",   // 添加结束时间字段
    shichang: 5400 // 添加shichang字段，默认值为5400秒
});

// 定义题目列表、当前试卷和试卷列表
const QuestionList = ref<{ question: string; answer: string }[]>([]);
const currentPaper = ref({
    Id: 0,
    Label: "",
    Kind: 0,
    Desc: "",
    Questions: [] as string[],
});
const paperList = ref<Array<typeof currentPaper.value>>([]);

// 加载状态
const isLoading = ref(false);

// 学生答卷信息
const studentAnswer = ref(null);
const examSubmitted = ref(false);

// 考试时间状态
const isExamActive = ref(true); // 默认考试是激活的
const isExamTimeOver = ref(false); // 考试时间是否已结束
const examTimeMessage = ref(""); // 考试时间相关信息

// 倒计时相关
const countdown = ref(0); // 初始值改为0
const countdownTimer = ref<NodeJS.Timeout | null>(null);
const formattedTime = ref("00:00:00");

// 挂载时执行的逻辑
onMounted(async () => {
    try {
        isLoading.value = true;
        // 获取授权信息
        const authorizationStr = localStorage.getItem("Authorization");
        const payload = CommonService.parseJwtPayload(authorizationStr);
        if (!payload) {
            router.push({ name: "login" });
            return;
        }
        currentUser.value = payload;

        // 获取路由参数
        const examIDStr = String(route.params.sn);
        console.log("examIDStr--------1----", examIDStr);
        // 查询考试信息
        const examInfoResult = await ExamService.getExamById(examIDStr);
        console.log("examInfoResult--------z----", examInfoResult);
        if (handleResult(examInfoResult) === false) {
            return;
        };

        exam.value = examInfoResult.Data;
        document.title = `${exam.value.Title} 考试`;

        // 解析题目并填充到QuestionList
        try {
            const questions = exam.value.Questions ? JSON.parse(exam.value.Questions) : [];
            QuestionList.value = questions.map((question: string) => ({
                question,
                answer: ""
            }));
        } catch (e) {
            console.warn("Failed to parse questions for exam:", exam.value.Id, e);
        }

        // 检查考试是否在有效时间内
        if (checkExamTimeValidity() == false) {
            return;
        };

        // 检查学生是否已完成试卷
        await checkStudentExamStatus(exam.value.Id, currentUser.value.sn);

        // 如果未完成试卷，则获取所有试卷（无论考试是否在有效期内都可以查看试卷内容）
        if (!examSubmitted.value) {
            // 只有在考试有效期内才开始倒计时
            if (isExamActive.value && !isExamTimeOver.value) {
                startCountdown(); // 开始倒计时
            }
        }
    } catch (error) {
        // alert("查询用户或试卷出错" + error);
    } finally {
        isLoading.value = false;
    }
});

// 组件卸载时清除定时器
onUnmounted(() => {
    if (countdownTimer.value) {
        clearInterval(countdownTimer.value);
    }
});

// 统一处理结果
const handleResult = (result: any) => {
    if (result.Code !== 1000) {
        alert(result.Title);
        return false;
    }
    if (result.Data.length === 0) {
        alert(result.Title);
        return false;
    }
    return true;
};

// 检查考试时间有效性
const checkExamTimeValidity = () => {
    const now = new Date();

    if (exam.value.Enable === 0) {
        isExamActive.value = false;
        isExamTimeOver.value = false;
        examTimeMessage.value = `本考试已经被禁止: ${exam.value.Title}`;
        return false;
    }
    // 如果没有设置考试时间，则默认考试是有效的
    if (!exam.value.StartAt && !exam.value.EndAt) {
        isExamActive.value = true;
        isExamTimeOver.value = false;
        examTimeMessage.value = "";
        return true;
    }

    // 检查开始时间
    if (exam.value.StartAt) {
        const startTime = new Date(exam.value.StartAt);
        if (now < startTime) {
            isExamActive.value = false;
            isExamTimeOver.value = false;
            examSubmitted.value = false
            examTimeMessage.value = `考试尚未开始，开始时间为: ${startTime.toLocaleString()}`;
            return false;
        }
    }

    // 检查结束时间
    if (exam.value.EndAt) {
        const endTime = new Date(exam.value.EndAt);
        if (now > endTime) {
            isExamActive.value = false;
            isExamTimeOver.value = true;
            examTimeMessage.value = `考试已结束，结束时间为: ${endTime.toLocaleString()}`;
            return false;
        }

        // 计算当前时间到结束时间的差值（秒）
        const timeDiff = Math.floor((endTime.getTime() - now.getTime()) / 1000);
        countdown.value = timeDiff > 0 ? timeDiff : 0;
        updateFormattedTime();
    }

    isExamActive.value = true;
    isExamTimeOver.value = false;
    examTimeMessage.value = "";
    return true;
};

// 检查学生考试状态
const checkStudentExamStatus = async (examId: number, studentSn: string) => {
    try {
        const response = await apiClient.get(`/api/examanswers/student/${studentSn}/exam/${examId}`);
        if (response.Code === 1000 && response.Data) {
            // 学生已完成试卷
            studentAnswer.value = JSON.parse(response.Data.Content);
            examSubmitted.value = true;

            // 填充答案到QuestionList
            QuestionList.value = studentAnswer.value.map((item: any) => ({
                question: item.question,
                answer: item.answer
            }));
        }
    } catch (error) {
        // 学生尚未完成试卷或者查询出错，继续正常流程
        console.log("学生尚未完成试卷或查询出错:", error);
    }
};

// 启动倒计时
const startCountdown = () => {
    // 清除已存在的定时器
    if (countdownTimer.value) {
        clearInterval(countdownTimer.value);
    }

    // 启动定时器
    countdownTimer.value = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--;
            updateFormattedTime();
        } else {
            // 时间到，自动提交试卷
            if (countdownTimer.value) {
                clearInterval(countdownTimer.value);
            }
            autoSubmitPaper();
        }
    }, 1000);
};

// 更新格式化时间显示
const updateFormattedTime = () => {
    const hours = Math.floor(countdown.value / 3600);
    const minutes = Math.floor((countdown.value % 3600) / 60);
    const seconds = countdown.value % 60;

    formattedTime.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

// 自动提交试卷
const autoSubmitPaper = async () => {
    // 检查考试是否仍在有效期内
    checkExamTimeValidity();
    if (!isExamActive.value) {
        alert("考试已不在有效期内，无法提交试卷");
        return;
    }

    if (examSubmitted.value) return;

    try {
        dialogMessage.value = "考试时间到，正在自动提交试卷...";
        openDialog();

        // 构造答卷内容
        const content = QuestionList.value.map((item, index) => {
            return {
                question: item.question,
                answer: item.answer,
                index: index + 1
            };
        });

        // 构造提交数据
        const requestData = {
            ExamId: exam.value.Id,
            ExamTitle: exam.value.Title,
            StudentName: currentUser.value.name,
            StudentSn: currentUser.value.sn,
            Content: JSON.stringify(content)
        };

        // 实际提交答案
        const result = await apiClient.post('/api/examanswers/', requestData);

        if (result.Code !== 1000) {
            throw new Error(result.Title || "提交答卷失败");
        }

        // 关闭对话框
        closeDialog();
        alert("考试时间到，试卷已自动提交！");
        examSubmitted.value = true;
    } catch (error) {
        closeDialog();
        alert("自动提交试卷出错:" + error);
    }
};

// 打开确认对话框
const openDialog = () => {
    confirmDialog.value?.open();
};
const closeDialog = () => {
    confirmDialog.value?.cancelFun();
};



// 提交答卷
const submitPaper = async () => {
    // 检查考试是否仍在有效期内
    checkExamTimeValidity();
    if (!isExamActive.value) {
        alert("考试已不在有效期内，无法提交试卷");
        return;
    }

    try {
        openDialog();

        // 构造答卷内容
        const content = QuestionList.value.map((item, index) => {
            return {
                question: item.question,
                answer: item.answer,
                index: index + 1
            };
        });

        // 构造提交数据
        const requestData = {
            ExamId: exam.value.Id,
            ExamTitle: exam.value.Title,
            StudentName: currentUser.value.name,
            StudentSn: currentUser.value.sn,
            Content: JSON.stringify(content)
        };

        // 实际提交答案
        const result = await apiClient.post('/api/examanswers/', requestData);

        if (result.Code !== 1000) {
            throw new Error(result.Title || "提交答卷失败");
        }

        // 关闭对话框
        closeDialog();
        alert("提交成功");
        examSubmitted.value = true;

        // 清除倒计时
        if (countdownTimer.value) {
            clearInterval(countdownTimer.value);
        }
    } catch (error) {
        closeDialog();
        alert("submitPaper 出错:" + error);
    }
};

// 添加确认提交函数
const confirmSubmit = () => {
    // 检查考试是否仍在有效期内
    checkExamTimeValidity();
    if (!isExamActive.value) {
        alert("考试已不在有效期内，无法提交试卷");
        return;
    }

    if (confirm("确定要提交答卷吗？提交后将无法修改！")) {
        submitPaper();
    }
};

// 禁止粘贴事件处理函数
const handlePaste = (event: ClipboardEvent) => {
    event.preventDefault();
    alert("为了保证考试的公平性，禁止粘贴答案，请手动输入。");
};

// 添加新题目
const addQuestion = () => {
    if (!examSubmitted.value) {
        QuestionList.value.push({
            question: "",
            answer: ""
        });
    }
};

</script>
<template>
    <div class="bg-surface-0 dark:bg-surface-900" style="font-size: 24px;">
        <!-- 显示考试学生信息 -->
        <div v-if="!params.isMe" class="student-info p-3 bg-blue-100">
            <h2>{{ currentUser.name }} 同学，学号: {{ currentUser.sn }}，欢迎参加《{{ exam.Title }}》考试。加油</h2>
        </div>

        <!-- 考试时间信息提示 -->
        <div v-if="examTimeMessage" class="p-3 bg-red-500 text-white text-center font-bold text-xl">
            {{ examTimeMessage }}
        </div>

        <!-- 倒计时显示 -->
        <div v-if="!examSubmitted && isExamActive && !isExamTimeOver"
            class="countdown-timer p-3 bg-orange-500 text-white text-center font-bold text-xl">
            距离考试结束还有: {{ formattedTime }}
        </div>

        <!-- 已提交提示 -->
        <div v-if="examSubmitted" class="p-3 bg-green-100 text-center">
            <h2>您已完成该试卷，无法重复提交。</h2>
        </div>

        <!-- 题目列表和答题区 -->
        <div class="flex flex-col p-4 md:p-10 items-center"
            style="background-image: linear-gradient(to top, #09203f 0%, #537895 100%);">
            <form style="width: 100%; max-width: 1900px;" @submit.prevent="submitPaper">
                <div v-for="(item, index) in QuestionList" :key="index" class="question-item">
                    <div class="question-text">
                        <strong>第{{ index + 1 }}题:</strong> {{ item.question }}
                    </div>
                    <Textarea :readonly="examSubmitted || !isExamActive || isExamTimeOver" placeholder="请输入您的答案..."
                        required class="answer-textarea" v-model="item.answer" @paste="handlePaste" />
                </div>

                <!-- 提交按钮 -->
                <div class="flex justify-center mt-4">
                    <Button v-if="!examSubmitted && isExamActive && !isExamTimeOver" @click="confirmSubmit"
                        type="button" class="p-3"
                        style="height: 4rem; width: 10rem; font-size: 18px;color: white; background-color: rgb(3, 107, 49);">
                        提交答卷
                    </Button>
                    <Button v-else-if="!examSubmitted && (isExamTimeOver || !isExamActive)" disabled type="button"
                        class="p-3"
                        style="height: 4rem; width: 10rem; font-size: 18px;color: white; background-color: gray;">
                        无法提交
                    </Button>
                </div>
            </form>

            <!-- 加载状态 -->
            <div v-if="isLoading" class="loading">加载中...</div>

            <!-- 页脚 -->
            <AppFooter class="mt-10" style="color: aliceblue"></AppFooter>
        </div>
        <!-- 确认对话框 -->
        <ConfirmDialog :message="dialogMessage" ref="confirmDialog" />
    </div>
</template>

<style scoped>
textarea:focus {
    background-color: white;
}

.loading {
    text-align: center;
    margin-top: 20px;
    font-size: 18px;
    color: white;
}

.student-info {
    text-align: center;
    font-size: 18px;
    color: rgb(3, 107, 49);
}

.exam-management {
    margin: 20px;
    padding: 20px;
    background-color: #f5f5f5;
    border-radius: 8px;
}

.question-item {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.question-text {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 15px;
    color: #333;
}

.answer-textarea {
    width: 100%;
    min-height: 120px;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 16px;
    resize: vertical;
    background-color: white;
}

.answer-textarea:focus {
    outline: none;
    border-color: #4d90fe;
    box-shadow: 0 0 5px rgba(77, 144, 254, 0.3);
}
</style>
